# _*_ coding:utf8 _*_
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
from django.utils import timezone

# Create your models here.
from teacher.models import Teacher

DAY_OF_THE_WEEK = (
    (0, u'周日'),
    (1, u'周一'),
    (2, u'周二'), (3, u'周三'), (4, u'周四'), (5, u'周五'), (6, u'周六')
)


class WeekDayField(models.SmallIntegerField):
    def __init__(self, *args, **kwargs):
        kwargs['choices'] = DAY_OF_THE_WEEK
        super(WeekDayField, self).__init__(*args, **kwargs)


class SClass(models.Model):
    """Student learning class"""

    weekday = WeekDayField(default=1)
    begin = models.TimeField()
    duration = models.DurationField(default=0)          # HH:MM:SS
    ccolor = models.CharField(max_length=10, blank=True)
    color_custom = models.BooleanField(default=False)
    teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name="teacher_classes", blank=True, null=True)
    fee = models.FloatField(default=0)  # 该堂课的课时费
    textbooks = models.ManyToManyField("STextBook", related_name="textbook_classes", blank=True)

    @property
    def end_time(self):
        newdate = datetime.combine(datetime.today(), self.begin) + self.duration
        return newdate.time()

    @property
    def weekday_str(self):
        return DAY_OF_THE_WEEK[self.weekday][1]

    def __unicode__(self):
        return ', '.join((DAY_OF_THE_WEEK[self.weekday][1], str(self.begin), str(self.duration)))


class STextBook(models.Model):
    textbook = models.CharField(max_length=40, default='Unknown')
    path = models.FileField(upload_to='textbook/files/', null=True)
    thumbnail = models.FileField(upload_to='textbook/thumb/', null=True)

    def __unicode__(self):
        return self.textbook


class SComment(models.Model):
    score = models.SmallIntegerField(default=1)
    textbook = models.ForeignKey('STextBook', on_delete=models.SET_DEFAULT, default=1, blank=True, null=True)
    content = models.CharField(max_length=300)

    modify_date = models.DateTimeField(auto_now=True)
    create_date = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.content


class Student(models.Model):
    """Student"""

    me = models.OneToOneField(User, on_delete=models.PROTECT, default=1)
    classes = models.ManyToManyField(SClass, related_name="class_students", blank=True)
    comments = models.ManyToManyField(SComment, related_name="comment_students", blank=True)
    fee = models.FloatField(default=0)  # 该学生的课时费

    def __unicode__(self):
        return str(self.me)
